package com.webframe.web.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.webframe.filter.FileFilterUtils;
import com.webframe.service.def.IMenuService;

/**
 * 菜单信息管理
 * @author lenovo
 *
 */
@SuppressWarnings("unchecked")
@Controller
@RequestMapping("/menu")
public class MenuController extends BaseController
{

	@Autowired
	private IMenuService	menuService;

	private Integer		startNum		= 0;

	private Integer		pageSize		= 20;

	private int				totalCount	= 0;

	private int				endNum		= 0;

	private String			id				= "";

	@RequestMapping
	public String index(HttpServletRequest request,HttpServletResponse response)
	{
		return "/menuManage/menuManage";
	}
	// 插入或删除菜单
	@SuppressWarnings("rawtypes")
	@RequestMapping("/doInsertOrModifyMenu")
	public String doInsertOrModifyMenu(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		Map params = request.getParameterMap();
		Iterator it = params.keySet().iterator();
		Map object = new HashMap();
		Object tmp;
		Boolean optResult = false;
		while (it.hasNext())
		{
			tmp = it.next().toString();
			object.put(tmp, ((Object[]) params.get(tmp))[0]);
		}
		try
		{
			optResult = menuService.doInsertOrUpdate(object);
		} catch (Exception e)
		{
			e.printStackTrace();// 处理异常
			optResult = false;
		} finally
		{
			doCommonPrint(response, optResult);
		}
		return null;
	}

	@RequestMapping("/doDeleteMenu")
	public String doDeleteMenu(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		Boolean optResult = false;
		String ID_ = request.getParameter("ID_");
		if (StringUtils.isNotEmpty(ID_))
		{
			try
			{
				optResult = menuService.doDeleteMenuByID(ID_);
			} catch (Exception e)
			{
				e.printStackTrace();
				optResult = false;
			} finally
			{
				doCommonPrint(response, optResult);
			}
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/doAddRole")
	public String doAddRole(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		Map params = request.getParameterMap();
		Iterator it = params.keySet().iterator();
		Map object = new HashMap();
		Object tmp;
		Boolean optResult = false;
		while (it.hasNext())
		{
			tmp = it.next().toString();
			object.put(tmp, ((Object[]) params.get(tmp))[0]);
		}
		try
		{
			optResult = menuService.doInsertNewRole(object);
		} catch (Exception e)
		{
			e.printStackTrace();
			optResult = false;
		} finally
		{
			doCommonPrint(response, optResult);
		}
		return null;
	}

	@RequestMapping("/doDeleteRole")
	public String doDeleteRole(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		Boolean optResult = false;
		String roleID = request.getParameter("ROLE_ID_");
		String menuID = request.getParameter("MENU_ID_");
		if (StringUtils.isNotEmpty(roleID)&&StringUtils.isNotEmpty(menuID))
		{
			try
			{
				optResult = menuService.doDeleteRole(menuID, roleID);
			} catch (Exception e)
			{
				e.printStackTrace();
				optResult = false;
			} finally
			{
				doCommonPrint(response, optResult);
			}
		}
		return null;
	}

	@SuppressWarnings("rawtypes")
	@RequestMapping("/getIconTree")
	public String getIconTree(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		String contextPath = request.getContextPath();
		String start = request.getParameter("start");
		String pageSize = request.getParameter("limit");
		if (StringUtils.isNotEmpty(start))
		{
			this.startNum = Integer.parseInt(start);
		}
		if (StringUtils.isNotEmpty(pageSize))
		{
			this.pageSize = Integer.parseInt(pageSize);
		}
		String menuIconPath = request.getSession().getServletContext().getRealPath("images/menuIcon");
		File file = new File(menuIconPath);
		File[] subFiles = file.listFiles(new FileFilterUtils());
		List fileList = new ArrayList();
		Map fileMap = null;
		if (null != subFiles && subFiles.length > 0)
		{
			for (int i = 0; i < subFiles.length; i++)
			{
				File tFile = subFiles[i];
				if (tFile.exists())
				{
					fileMap = new HashMap<String, String>();
					fileMap.put("name", tFile.getName());
					String path = tFile.getAbsolutePath().replace("\\", "/");
					path = contextPath+ path.substring(path.indexOf("webContent") + 10,path.length());
					fileMap.put("path", path);
					fileMap.put("leaf", !tFile.isDirectory());
					fileList.add(fileMap);
				}
			}
			this.totalCount = fileList.size();
			if (this.startNum + this.pageSize <= this.totalCount)
			{
				this.endNum = this.startNum + this.pageSize;
			} else
			{
				this.endNum = this.totalCount;
			}
		}
		// do page
		List temp = new ArrayList();
		if (null != fileList && fileList.size() > 0)
		{
			for (int i = this.startNum; i < this.endNum; i++)
			{
				temp.add(fileList.get(i));
			}
		}
		fileList = temp;
		PrintTreeJson(response, fileList);
		return null;
	}

	@SuppressWarnings("rawtypes")
	public void PrintTreeJson(HttpServletResponse response, List list)
	{
		if (null == list) return;
		Map map = null;
		Boolean flag = false;
		StringBuffer sb = new StringBuffer();
		sb.append("{totalCount:" + this.totalCount);
		sb.append(",images:[");
		try
		{
			if (null != list && list.size() > 0)
			{
				for (int i = 0; i < list.size(); i++)
				{
					map = new HashMap();
					map = (Map) list.get(i);
					String name = (String) map.get("name");
					String path = (String) map.get("path");
					if (flag) sb.append(",");
					sb.append("{");
					sb.append("name:'");
					sb.append(name);
					sb.append("',");
					sb.append("path:'");
					sb.append(path);
					sb.append("'");
					sb.append("}");
					flag = true;
				}
				sb.append("]}");
				outWrite(response, sb.toString());
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	@SuppressWarnings("rawtypes")
	public void PrintComboJson(HttpServletResponse response, List list)
				throws IOException
	{
		Map map = null;
		Boolean flag = false;
		String sortInfo = "-1";
		StringBuffer sb = new StringBuffer();
		if (list.isEmpty())
		{
			sb.append("{datas:[{name:'第一位',valtext:'0'},{name:'最后一位',valtext:'-1'}],sortInfo:'-1'}");
		}
		try
		{
			if (null != list && list.size() > 0)
			{
				sb.append("{datas:[{name:'第一位',valtext:'0'}");
				Boolean oneRecordFlag = (list.size() == 1)
							&& this.id.equals(((Map) list.get(0)).get("ID_"));
				if (!oneRecordFlag) sb.append(",");
				for (int i = 0; i < list.size(); i++)
				{
					map = new HashMap();
					map = (Map) list.get(i);
					String ID = (String) map.get("ID_");
					if (ID.equals(this.id))
					{
						if (i == 0)
						{
							sortInfo = "0";
						} else if (i == list.size() - 1)
						{
							sortInfo = "-1";
						} else
						{
							sortInfo = ((Map) list.get(i - 1)).get("POSITION_").toString();
						}
						continue;
					}
					String valtext = "";
					if (null != map.get("POSITION_")
								&& !"".equals(map.get("POSITION_"))
								&& !"null".equals(map.get("POSITION_")))
					{
						valtext = map.get("POSITION_").toString();
					}
					String name = (String) map.get("NAME_");
					if (flag) sb.append(",");
					sb.append("{");
					sb.append("name:'");
					sb.append(name);
					sb.append("',");
					sb.append("valtext:'");
					sb.append(valtext);
					sb.append("'");
					sb.append("}");
					flag = true;
				}
				sb.append(",{name:'最后一位',valtext:'-1'}],sortInfo:'");
				sb.append(sortInfo);
				sb.append("'");
				sb.append("}");
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		outWrite(response, sb.toString());
	}

	/**
	 * 作用于前台combo排序 增加新菜单:pid 修改菜单 :params
	 */
	@SuppressWarnings("rawtypes")
	@RequestMapping("/doSort")
	public String doSort(HttpServletRequest request, HttpServletResponse response)
				throws Exception
	{
		String pid = request.getParameter("pid");
		String params = request.getParameter("params");
		if (null != pid && !"".equals(pid))
		{
			List list = menuService.GetMenusByPID(pid);
			PrintComboJson(response, list);
		} else if (null != params && !"".equals(params))
		{
			pid = params.split(",")[0];
			this.id = params.split(",")[1];
			List list = menuService.GetMenusByPID(pid);
			PrintComboJson(response, list);
		}
		return null;
	}

	public void doCommonPrint(HttpServletResponse response, Boolean optResult)
				throws IOException
	{
		StringBuffer sb = new StringBuffer();
		if (optResult)
		{
			sb.append("{success:true}");
		} else
		{
			sb.append("{success:false}");
		}
		outWrite(response, sb.toString());
	}
}
